package src

import (
	"simple-system/src/sql"
)

const (
	dataDir          = "./data/"
	homeDataFilename = dataDir + "home.dat"
)

var (
	configPath       = "./config/config.json"
	config           = &Config{Port: ":80"}
	lastProcFileName = "" // 最后操作文件
	homeMap          = make(map[string]*listInfo)
	sqlMap           = make(map[string]sql.Sql)
	home             = &homeInfo{
		List: []listInfo{
			listInfo{
				Name: "测试",
				Path: "test",
				Title: []titleInfo{
					titleInfo{
						Name: "表头",
						Key:  "key",
					},
				},
			},
		},
	}
)

const (
	homeHtml = `
<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <title>Home</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <style>
	button{background: yellowgreen; padding: 8px;font-size: 30px;  border-radius: 100px;}
	input{padding: 8px; background: #f8f8f8; border-radius: 5px;}
	input:focus{padding: 8px; background: #ffc0cb} /*获取焦点时*/
	input[value][style="1"]{background: blue}   /*style ~= "1" 其中一个相等*/

	.zhezhao{
		position: fixed;
		left: 0px;
		top: 0px;
		background: rgb(140, 140, 140);
		width: 100%%;
		height: 100%%;
		opacity: 1;
	}
	.tankuang{
		position: relative;
		background: #fff;
		width: 50%%;
		height: 80%%;
		border-radius: 5px;
		margin: 5%% auto;
	}
	#header{
		height: 40px;
	}
	#header-right{
		position: absolute;
		width: 25px;
		height: 25px;
		border-radius: 5px;
		background: red;
		color: #fff;
		right: 5px;
		top: 5px;
		text-align: center;
	}

  </style>
</head>

<body>
%s
	<div class="zhezhao" id='zhezhao'>
		<div class="tankuang">
			<div id="header">
				%s
			</div>
		</div>
	</div>
</body>

<script>
	function getPath(path) {
		console.log("getPath", path)
		window.location.href = "/?path=" + path;
	}
	
	document.getElementById('zhezhao').style.display="none";
	editNowIdx = 0
	path = "%s"
	addItemIdx = %d

	function showHidder(){
		document.getElementById('zhezhao').style.display="";
	}

	function hidder(){
		document.getElementById('zhezhao').style.display="none";
	}
	
	function newItem(){
		for (let i=1; ; i++) {
			item = document.getElementById("edit_"+i)
			if (item) {
				item.value = ""
			} else {
				break
			}
		}
		editNowIdx = addItemIdx
		document.getElementById('zhezhao').style.display=""
	}
	
	function editItem(idx){
		let list = document.getElementById("colume_list_"+idx)
		for (let i=1; ; i++) {
			item = document.getElementById("edit_"+i)
			if (item) {
				item.value = list.childNodes[i].innerHTML
			} else {
				break
			}
		}
		editNowIdx = idx
		document.getElementById('zhezhao').style.display=""
	}
	
	function removeItem(idx) {
		if (!confirm("确认删除？")) {
			return
		}
		let j = { "#idx" : idx, "#path" : path }
		console.log(j)
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				// alert(this.responseText)
				if (xhr.status != 200) {
					alert(this.responseText)
					return
				}
				window.location.href = "/?path=" + path
		    }
		};
		xhr.open( // 打开链接
			"delete",
			"/editItem", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(JSON.stringify(j)); //发送请求 将json写入send中sss
	}
	
	function saveItem() {
		let j = { "#idx" : editNowIdx, "#path" : path }
		for (let i=1; ; i++) {
			item = document.getElementById("edit_"+i)
			if (item) {
				j[item.name] = item.value || ""
			} else {
				break
			}
		}
		console.log(j)
		
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				// alert(this.responseText)
				if (xhr.status != 200) {
					alert(this.responseText)
					return
				}
				window.location.href = "/?path=" + path
		    }
		};
		xhr.open( // 打开链接
			"post",
			"/editItem", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(JSON.stringify(j)); //发送请求 将json写入send中sss
	}
</script>
</html>
`
)

const (
	setHtml = `<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <title>settting</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <style>
	button{background: yellowgreen; padding: 8px;font-size: 30px;  border-radius: 100px;}
	input{padding: 8px; background: #f8f8f8; border-radius: 5px;}
	input:focus{padding: 8px; background: #ffc0cb} /*获取焦点时*/
	input[value][style="1"]{background: blue}   /*style ~= "1" 其中一个相等*/
  </style>
</head>

<body>
<form action="" onsubmit="return saveSet()">
<a href="/">返回首页</a>
<button type="submit">保存</button>

%s

</form>
<button onclick="addList()">+</button>
</body>

<script>
	maxId = {}
	function addNewCol(pid) {
		// 获取所有的input元素 列表
		div = document.getElementById(pid)
		
		max = maxId[pid]
		if (!max) {
			max = div.childNodes.length + 1
		}
		maxId[pid] = max + 1
		
		cd = document.createElement("div")
		cd.id = pid + "_" + max
		
		l = document.createElement("label")
		l.innerText = "列表名："
		cd.appendChild(l)
		
		i1 = document.createElement("input")
		i1.value = "列表名"
		i1.type = "text"
		i1.name = "name"
		i1.pattern = "^[\u4E00-\u9FA5A-Za-z0-9_]+$"
		cd.appendChild(i1)
		
		l1 = document.createElement("label")
		l1.innerText = "列表关键字："
		cd.appendChild(l1)

		i1 = document.createElement("input")
		i1.value = "key"
		i1.type = "text"
		i1.name = "key"
		i1.pattern = "^[A-Za-z0-9]+$"
		cd.appendChild(i1)

		i1 = document.createElement("input")
		i1.value = "删除"
		i1.type = "button"
		i1.onclick=delCol
		i1.id = pid + " " + cd.id
		cd.appendChild(i1)
		
		div.appendChild(cd)
	}
	function delCol(pid="", id="") {
		if (!confirm("确认删除？")) {
			return
		}
		if (!id) {
			ids = event.target.id.split(" ")
			pid = ids[0]
			id = ids[1]
		}
		if (pid && id) {
			// 获取所有的input元素 列表
			div = document.getElementById(pid)
			child = document.getElementById(id)
			div.removeChild(child)
		}
	}
	
	function constans(str, s) { 
		sum = 0
		for (j=0;j<str.length;j++) {
			if (str[j] == s) { sum += 1}
		}
		return sum
	}
	
	function getAll() {
		list = document.getElementsByTagName("div")
		newList = []
		for (i=0;i<list.length;i++) {
			if (constans(list[i].id , '_') == 2 ) {
				newList.push(getOne(list[i]))
			}
		}
		return newList
	}
	
	function getOne(div) {
		items = div.getElementsByTagName("input")
		if (!items) {
			return
		}
		item = { title : [] }
		m = 0
		item[items[m+1].name] = items[m+1].value
		item[items[m].name] = items[m].value
		last = items[m+3].name // 跳过一个按钮
		n = -1
		for (k=m+3;k<items.length; k++ ) {
			if (items[k].type == "text") {
				if (items[k].name == last) {
					n += 1
					item.title[n] = {}
				}
				item.title[n][items[k].name] = items[k].value
			}
		}
		return item
	}
	
	function fallback() {
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				window.location.href = "/config";
		    }
		};
		xhr.open( // 打开链接
			"get",
			"/fallback", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(); 
	}
	
	function saveSet() {
		json = JSON.stringify({'list': getAll()})
		console.log(json)
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				if (xhr.status != 200) {
					alert(this.responseText)
				} else {
					alert("save ok!")
					window.location.href = "/config";
				}
		    }
		};
		xhr.open( // 打开链接
			"post",
			"/config", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(json); //发送请求 将json写入send中sss
		return false
	}
	
	function addList() {
		list = getAll()
		item = {}
		t = list[list.length - 1].title[0]
		item.title = [{name: t.name, key : t.key }]
		item.name = "新增数据" + new Date().toLocaleString()
		item.path = "new path"
		list.push(item)
		json = JSON.stringify({'list': list })
		console.log(json)
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				// alert(this.responseText)
				if (xhr.status != 200) {
					alert(this.responseText)
					return
				}
				window.location.href = "/config";
		    }
		};
		xhr.open( // 打开链接
			"post",
			"/config", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(json); //发送请求 将json写入send中sss
	}
	
	function removeList(idx) {
		if (!confirm("确认删除整个导航栏？")) {
			return
		}
		console.log("remobe", idx)
		list = getAll()
		newList = []
		for (i=0;i<list.length;i++) {
			if (i != idx) {
				newList.push(list[i])
			} 
		}
		json = JSON.stringify({'list': newList })
		console.log(json)
		let xhr = new XMLHttpRequest(); // 创建XHR对象
		xhr.onreadystatechange = function () {
		    if (xhr.readyState == 4) { // 4表示此次请求结束
		    	console.log("后端返回的结果："+this.responseText);
				if (xhr.status != 200) {
					alert(this.responseText)
					return
				}
				window.location.href = "/config";
		    }
		};
		xhr.open( // 打开链接
			"post",
			"/config", // 后端地址
			true
		);
		xhr.setRequestHeader("Content-type", "application/json");
		xhr.send(json); //发送请求 将json写入send中sss
	}	
	
</script>
</html>`

	setNewItem = `
	导航栏名称：<input type="text" name="name" value="%s" pattern="^[\u4E00-\u9FA5A-Za-z0-9-]+$"> 
	路径：<input type="text" name="path" value="%s" pattern="^[A-Za-z0-9- .]+$">
	<input type="button" onclick="addNewCol('%s')" style="background: rgba(0,150,150,1)" value="增加">
	<hr>
`
	addNewCol = `
	<div id="%s">
		<br>
		列表名：<input type="text" name="name" value="%s" pattern="^[\u4E00-\u9FA5A-Za-z0-9_]+$"> 
		列表关键字：<input type="text" name="key" value="%s" pattern="^[A-Za-z0-9]+$">
		<input type="button" onclick="delCol('%s', '%s')" value="删除">
	</div>
`

	addDetails = `
<details %s>
	<summary><b %s >%s 	</b><input type="button" onclick="removeList(%d)" value=" 删 除 " > </summary>
	<div id="%s">
		%s
	</div>
</details>
<hr>
`

	// <td>内容</td>
	// <tr>一行</tr>
	tableHtml = `
	<details>
		<summary>%s</summary>
		<table cellspacing="0" border="1">
			<tr align="center" style="font-weight: bold" >%s</tr>
			%s
		</table>
	<br>
	</details>
`
)
